package logic

import (
	"api/internal/svc"
	"api/internal/types"
	"context"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"goods_srv/goods"
	"order_srv/order"
)

type CreateOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderRequest) (resp *types.Response, err error) {
	// 判断商品是否存在
	goodsResp, err := l.svcCtx.GoodsSrv.DetailGoods(l.ctx, &goods.DetailGoodsRequest{GoodsId: req.GoodsId})

	if err != nil {
		return &types.Response{
			Code: -1,
			Msg:  "服务器错误",
			Data: nil,
		}, nil
	}
	if goodsResp.GoodsID == 0 {
		return &types.Response{
			Code: -2,
			Msg:  "商品不存在",
			Data: nil,
		}, nil
	}

	//库存是否充足
	res, _ := l.svcCtx.GoodsSrv.DetailGoods(l.ctx, &goods.DetailGoodsRequest{GoodsId: req.GoodsId})

	if res.GoodsStock < req.Num {
		return &types.Response{
			Code: -4,
			Msg:  "商品库存不足",
			Data: nil,
		}, nil
	}
	//如果商品不在购物车中，则添加购物车，负则更新购物车数量
	userId := l.ctx.Value("userId").(int)
	orderSn := uuid.NewString() //订单编号
	amount := goodsResp.GoodsPrice * float32(req.Num)

	OrderResp, err := l.svcCtx.OrderSrv.CreateOrder(l.ctx, &order.CreateOrderRequest{
		UserId:  int64(userId),
		OrderSn: orderSn,
		Amount:  amount,
		Payment: req.PayMent,
	})
	if err != nil {
		return &types.Response{
			Code: -3,
			Msg:  "服务器错误",
			Data: nil,
		}, nil
	}
	return &types.Response{
		Code: 2,
		Msg:  "订单创建成功",
		Data: map[string]interface{}{
			"order_id": OrderResp.OrderId,
		},
	}, nil
}
